

Core.Items = Core.List.extend ({
	
	init: function (options) {
	
		var self = this;
		
		var container = self.container = $('div.bookcase');
		
		// New Item Form
		$('a.butPrimary:contains("Add Item")').click(function() {
			self.showItemDependencyForm();
			return false;
		});
		
		// Add item button
		container.find('a:contains("Add")').click(function() {
			// Green button loading anim
			$('div.buttons').addClass('disabled');

			self.ItemDependencyForm.save({
				success: function (response) {
					alert('success'+response);
					//self.addItemToBillOfMaterials();
				},
				error: function (response) {
					alert('error'+response);
				}
			});
			/*
			self.newExpenseForm.save({
				success: function (response) {
					self.clearErrors();
					var expenseid = response.expenseid;
					self.addExpenseToTable(expenseid);
				},
				error: function (response) {
					var msg = response.error.htmlentities();
					container.find('#item-msg').html(msg).show().addClass('error');
				}
			});
			*/
			return false;
		});

		
		// Cancel Button
		$("#item-add-cancel").click(function() {

			self.ItemDependencyForm.clear();

			/*
			// clear Item Code selection
			codeCombobox.closeAll();
			codeCombobox.selectOption(0);

			$('div.item_code-container')[0].innerHTML = '';

			// clear Item Name selection
			nameCombobox.closeAll();
			nameCombobox.selectOption(0);

			$('div.item_name-container')[0].innerHTML = '';

			
			self.container.find('input[name=ItemDependency[quantity]]').val('');
			*/
			
			$("#test").hide();
			
			

			
			
			$('a.butPrimary:contains("Add Item")').show();
			
			return false;
		});
		
		self.ItemDependencyForm = new Core.Items.Form(self, $('#item-form-container'));
		


	},
	
	showItemDependencyForm: function() {
		$('div.bookcase').show().find('input:visible:first').focus();
		$('a.butPrimary:contains("Add Item")').hide();
	},
	
	hideItemDependencyForm: function() {
		$('div.bookcase').hide();
		this.ItemDependencyForm.clear();
		$('a.butPrimary:contains("Add Item")').show();
	},

	
	addItemToBillOfMaterials: function() {
		
		$('table.index tr.no-results').remove();
		var $row = $(self._expenseRowContent(response));

		var $firstRow = $('table.index tbody tr:first');
		if (!$firstRow.hasClass('even')) {
			$row.addClass('even');
		}
		$('table.index tbody').prepend($row);
		self.highlightRow($row);
	
		// Load the new total from XML and update the total.
		$('.expense_total').html(response.expense_total_formatted);
		$('.expense_total').attr('amount', response.expense_total);

	}
	
	
});

Core.Items.Form = Class.extend({
	defaults: {
		saveUrl: '../ajax/saveItemDependency'
	},
	
	// Constructor
	init: function(page, container, options) {
		this.options = jQuery.extend({}, this.defaults, options);
		this.page = page;
		this.container = container;
		
		this.buildComboBoxes();
		//this.tpl = Fresh.Util.getTemplate('#expense-form');

		// Date/Calendar
		//FbCalendar.formatType = Fresh.Preferences.get('date_format');
		//FbCalendar.borderColor = '#' + Fresh.Preferences.get('bluebox');
	},
	
	buildComboBoxes: function() {
		var self = this;
		var container = this.container;

		// Item Code combobox
		var itemCodeList = [];
		
		$.each(itemCodeData, function(id, code) {
			itemCodeList.push({text: code.htmlentities(), value: id});
		});
		
		var comboContainer = container.find('div.item_code-container')[0];
		
		this.codeCombobox = new dhtmlXCombo(comboContainer, 'dependency_id', '133px');
		this.codeCombobox.enableFilteringMode(true);
		this.codeCombobox.addOption(itemCodeList);
		
		$(this.codeCombobox.DOMelem_input).attr('maxlength', 25).addClass('expense-vendor');

		this.codeCombobox.attachEvent('onSelectionChange', function() {
			selectText = itemNameData[self.codeCombobox.getSelectedValue()];
			self.nameCombobox.setComboText(selectText);
		});
		
		// Item Name combobox
		var itemNameList = [];
		
		$.each(itemNameData, function(id, name) {
			itemNameList.push({text: name.htmlentities(), value: id});
		});
		
		var comboContainer = container.find('div.item_name-container')[0];
		
		this.nameCombobox = new dhtmlXCombo(comboContainer, 'dependency_id', '133px');
		this.nameCombobox.enableFilteringMode(true);
		this.nameCombobox.addOption(itemNameList);
		//nameCombobox.loadXML('/cloverdale/xml/itemNames', true);

		$(this.nameCombobox.DOMelem_input).attr('maxlength', 25).addClass('expense-vendor');

		this.nameCombobox.attachEvent('onSelectionChange', function() {
			selectedText = itemCodeData[self.nameCombobox.getSelectedValue()]
			self.codeCombobox.setComboText(selectedText);
		});
	},


	save: function(callbacks) {
		alert('saving..');
		
		var data = {};
		
		data['item']['itemId'] = this.container.find('input[name=item_id]').val();
		data['item']['dependentId'] = this.container.find('input[name=dependent_id]').val();
		data['item']['qntyNeeded'] = this.container.find('input[name=quantity]').val();
		
		$.ajax({
			url: this.options.saveUrl,
			type: 'POST',
			data: data, 
			dataType: 'json',
			success: function (response) {
				//addCategoryToComboBoxesIfCreated(response.categoryid);

				// Update vendor list with new vendor, if one was created / non-blank
				//if (!existVendor && newVendor != '') {
				//	var vendorOption = { value: newVendor, text: newVendor.htmlentities() };
				//	self.page.vendorList.push(vendorOption);
				//	self.vendorCombobox.addOption([vendorOption]);
				//}
				//self.page.refreshComboboxes(response.categoryid);

				//self.clear();
				this.container.find('input:visible:first').focus();
				alert(response);
				callbacks.success(response);
			},
			error: function (request) {
				alert(request.responseText);
				var response = JSON.parse(request.responseText);
				var errorField = response.error_field;
				if (errorField == "date" || errorField == 'end_date') {
					self.container.find('input.expense-' +  errorField + ', select.expense-' + errorField)
						.addClass('errorInput');
				} else {
					var elem = self.container.find('input.expense-' +  errorField + ', select.expense-' + errorField),
						method = (self.onErrorFocus) ? 'focus' : 'blur';
					elem.addClass('errorInput')[method]();
				}
				callbacks.error(response);
			},
			complete: function (request) {
				$('div.buttons').removeClass('disabled');
				if (callbacks.complete) {
					callbacks.complete(request);
				}
			}
		});

		
	},
	
	// Clear the contents of the form
	clear: function() {
		var self = this;

		//this.container.find('input.errorInput:visible').removeClass('errorInput');

		// This closes all comboboxes - not just vendor
		this.codeCombobox.closeAll();
		this.codeCombobox.selectOption(0);
		
		this.nameCombobox.closeAll();
		this.nameCombobox.selectOption(0);

		this.container.find('input[name=quantity]').val('');
	},
	
	load: function(attrs) {
		// Generate template from attrs

		this.mapper = new Core.ui.FieldMapper({
			fields: this.options.fields,
			parent: this.container
		});

		this.initializeFields(attrs);
	}
	


	
});
